package at.com.vn.chess.element;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.Timer;

import at.com.vn.chess.listener.TimerListener;
import at.com.vn.chess.util.Const;

public class StopWatch extends JButton implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2457381001463258348L;
	// Timer counter
	int totalRemainTime; // How many milliseconds remain in the countdown.
	int remainTime;
	long lastUpdate; // When count was last updated
	Timer timer; // Updates the count every second
	NumberFormat format; // Format minutes:seconds with leading zeros

	private TimerListener mListener;

	Font ver = new Font( "Verdana", Font.LAYOUT_LEFT_TO_RIGHT,
			Const.STOP_WATCH_FONT_SIZE );

	public StopWatch( Rectangle pasteArea ) {
		super();
		setBorderPainted( false );
		setContentAreaFilled( false );
		setFocusPainted( false );
		setBounds( pasteArea.x, pasteArea.y, pasteArea.width, pasteArea.height );
		setFont( ver );
		setForeground( new Color( 192, 192, 181 ) );
		setBackground( new Color( 74, 13, 4 ) );
		setOpaque( true );
		setVerticalTextPosition(SwingConstants.CENTER);
		setHorizontalTextPosition(SwingConstants.LEFT);

		totalRemainTime = Const.COUNT_DOWN_START_POINT_TOTAL;
		remainTime = Const.COUNT_DOWN_START_POINT_PRIVATE;
		
		init();	
	}

	public void addTimeZeroListener( TimerListener listener ) {
		mListener = listener;
	}

	public void actionPerformed( ActionEvent e ) {
		updateDisplay();
	}

	private void init() {
		// Obtain a NumberFormat object to convert number of minutes and
		// seconds to strings. Set it up to produce a leading 0 if necessary
		format = NumberFormat.getNumberInstance();
		format.setMinimumIntegerDigits( 2 ); // pad with 0 if necessary

		// Create a timer to call the actionPerformed( ) method immediately,
		// and then every 1000 milliseconds. Note we don't start the timer yet.
		timer = new Timer( Const.ONE_SECOND, this );
		timer.setInitialDelay( 0 ); // First timer is immediate.
		
		resume();
		pause();
		
		updateDisplay();
	}

	// Start or resume the countdown
	public void resume() {
//		isPaused = false;
		// Restore the time we're counting down from and restart the timer.
		lastUpdate = System.currentTimeMillis();
		timer.start(); // Start the timer
	}

	// Pause the countdown
	public void pause() {
		// Subtract elapsed time from the remaining time and stop timing
		timer.stop(); // Stop the timer
		long now = System.currentTimeMillis();
		totalRemainTime -= ( now - lastUpdate );
		remainTime = Const.COUNT_DOWN_START_POINT_PRIVATE;		
	}
	
	public void reset() {
		totalRemainTime = Const.COUNT_DOWN_START_POINT_TOTAL;
		remainTime = Const.COUNT_DOWN_START_POINT_PRIVATE;
		lastUpdate = System.currentTimeMillis();
		updateDisplay();
	}

	// Update the displayed time. This method is called from actionPerformed( )
	// which is itself invoked by the timer.
	void updateDisplay() {
		long now = System.currentTimeMillis(); // current time in ms
		long elapsed = now - lastUpdate; // ms elapsed since last update
		totalRemainTime -= elapsed; // adjust remaining time
		remainTime -= elapsed; // adjust remaining time
		lastUpdate = now; // remember this update time

		// Convert remaining milliseconds to mm:ss format and display
		if ( totalRemainTime < 0 ) {
			totalRemainTime = 0;
		}
		
		if ( remainTime < 0 ) {
			remainTime = 0;
		}

		int minutes = ( int ) ( totalRemainTime / Const.ONE_MINUTE );
		int seconds = ( int ) ( ( totalRemainTime % Const.ONE_MINUTE ) / Const.ONE_SECOND );

		int minutes2 = ( int ) ( remainTime / Const.ONE_MINUTE );
		int seconds2 = ( int ) ( ( remainTime % Const.ONE_MINUTE ) / Const.ONE_SECOND );
		setText( new StringBuilder().append( format.format( minutes ) )
				.append( ":" ).append( format.format( seconds ) ).append( "  " )
				.append( format.format( minutes2 ) ).append( ":" )
				.append( format.format( seconds2 ) ).toString() );

		// If we've completed the countdown, beep and display new page
		if ( remainTime == 0 || totalRemainTime == 0 ) {
			// Stop updating now.
			mListener.timeZero();
			timer.stop();
		}
	}

	public void setRemainTime( int time ) {
		totalRemainTime = time;
		remainTime = Const.COUNT_DOWN_START_POINT_PRIVATE;

		// Neu la nhung giay cuoi cung  
		if( totalRemainTime < remainTime ) {
			remainTime = totalRemainTime;	
		}
	}

	public int getRemainTime() {
		return ( int ) totalRemainTime;
	}
}
